package com.pm2.controller.project;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.pm2.dao.project.ProjectDao;
import com.pm2.entity.project.Project;
import com.pm2.entity.project.vo.MeetDetailVo;
import com.pm2.entity.weekMeet.TaskAttachment;
import com.pm2.entity.weekMeet.TaskAttachmentVo;
import com.pm2.service.performance.PerformanceService;
import com.pm2.service.project.TaskAttachmentService;
import com.shuohe.entity.system.user.User;
import com.shuohe.util.date.SDate;
import com.shuohe.util.poi.POI;
import com.shuohe.util.returnBean.ReturnBean;

import lombok.extern.slf4j.Slf4j;

@Controller  
@RequestMapping("/pm2/project/*")  
@Slf4j
public class ProjectController {
    private static String rfPath="/upfile/files/";
	
	private static String riPath="/upfile/img/";
	
	private static String rePath="/upfile/excel/";
	
	private static String rzPath="/upfile/zip/";
	
	@Value("${myPath.filePath}")
    private String filePath;
	
	@Value("${myPath.imgPath}")
    private String imgPath;
	
	@Value("${myPath.excelPath}")
    private String excelPath;
	
	@Value("${myPath.zipPath}")
    private String zipPath;

	@Autowired
	private ProjectDao projectDao; 
	
	@Autowired
	private PerformanceService performanceService; 
	
	@Autowired
	private TaskAttachmentService taskAttachmentService; 
	
	
	@RequestMapping(value="project/save.do")  
    public @ResponseBody ReturnBean companySave(HttpServletRequest request,HttpServletResponse response){
		Gson reGson = new GsonBuilder()
				.setDateFormat("yyyy-MM-dd")  
				.create();  
		String data = request.getParameter("data").replaceAll("\"\"", "null");
		Project project = reGson.fromJson(data, new TypeToken<Project>(){}.getType());
		try
		{
			projectDao.save(project);
			return new ReturnBean(true,"");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return new ReturnBean(false,e.getMessage());
		}
	}
	@RequestMapping(value="project/edit.do")  
    public @ResponseBody ReturnBean companyEdit(HttpServletRequest request,HttpServletResponse response){
		Gson reGson = new GsonBuilder()
				.setDateFormat("yyyy-MM-dd")  
				.create();  
		String data = request.getParameter("data").replaceAll("\"\"", "null");
		Project project = reGson.fromJson(data, new TypeToken<Project>(){}.getType());
		try
		{
			projectDao.save(project);
			return new ReturnBean(true,"");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return new ReturnBean(false,e.getMessage());
		}
	}
	@RequestMapping(value="project/delete.do")  
    public @ResponseBody ReturnBean companyDelete(@RequestParam("id") int id){
	
		try
		{
			projectDao.deleteById(id);
			return new ReturnBean(true,"删除成功");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return new ReturnBean(false,e.getMessage());
		}
	}
	
	/**
	 * 绩效结算
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="performanceSettleAccounts.do")  
    public @ResponseBody ReturnBean performanceSettleAccounts(HttpServletRequest request,HttpServletResponse response){
		String str = request.getParameter("data");
		Gson gson = new Gson();
		List<MeetDetailVo> list = gson.fromJson(str, new TypeToken<List<MeetDetailVo>>(){}.getType());
		System.out.println(list);
		performanceService.performanceCount(list);
		return new ReturnBean(true,"结算成功");
	}
	
	
	@RequestMapping(value="changeCommitStatus.do")  
    public @ResponseBody ReturnBean changeCommitStatus(@RequestParam("master_plan_id") int id
    		,@RequestParam("commit_status") String status){
		    performanceService.changeCommitStatus(id,status);
			return new ReturnBean(true,"操作成功");
	}
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportExcel.do", method = RequestMethod.GET)
    public void exportExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String fileName = "绩效列表.xls";//文件名称必须带后缀
		//1.设置excel表头
		ArrayList<String> headers = new ArrayList<String>();
		headers.add("任务所属人");
		headers.add("任务绩效");
		headers.add("时间间隔");
		headers.add("任务内容");
		headers.add("结算周期");
		headers.add("结算起始日期");
		headers.add("结算结束日期");
		headers.add("结算时间");
		//设置数据库字段的表头
		ArrayList<String> keys = new ArrayList<String>();
		keys.add("name");
		keys.add("taskPerformance");
		keys.add("duration");
		keys.add("taskContent");
		keys.add("period");
		keys.add("startDate");
		keys.add("endDate");
		keys.add("doTime");
		List<Map<String,Object>> searchList = (List<Map<String, Object>>) request.getSession().getAttribute("searchResult");
		System.out.println(searchList);
		POI poi = new POI();
		poi.setFile_name(fileName);
		poi.setTable("sheet1");
	 	poi.setHeaders(headers);
	 	poi.setKeys(keys);
		//数据库检索及流输出
		poi.setData(searchList);
		POI.Rb rb = poi.createExcel();
		String xfileName = URLEncoder.encode(fileName, "utf-8");
		response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;filename=" + xfileName);
        OutputStream out = response.getOutputStream();
        rb.getExcel().write(out);
        rb.getExcel().close();
        out.close(); 
		
	}
	
	//个人任务附件上传
	@RequestMapping(value = "uploadTaskFile.do")
	@ResponseBody
	public ReturnBean uploadEqpMaintainRecord(HttpServletRequest request) {
		User user = (User)request.getSession().getAttribute("user");
		String taskId = request.getParameter("taskId");
		List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file"); 
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        List<TaskAttachment> list = new ArrayList<TaskAttachment>();
        for (int i =0; i< files.size(); ++i) { 
            file = files.get(i); 
            if (!file.isEmpty()) { 
            	TaskAttachment ta = new TaskAttachment();
            	String fileName = System.currentTimeMillis()+"_"+file.getOriginalFilename();
            	String path = imgPath + fileName;
            	String suffixName = fileName.substring(fileName.lastIndexOf("."));
                try { 
                    byte[] bytes = file.getBytes(); 
                    stream = 
                            new BufferedOutputStream(new FileOutputStream(new File(path))); 
                    stream.write(bytes); 
                    stream.close(); 
                    ta.setFileName(fileName);
                    ta.setFilePath(riPath+fileName);
                    ta.setFileRealPath(path);
                    ta.setFileType(suffixName);
                    ta.setTaskId(Integer.valueOf(taskId));
                    ta.setUploadTime(SDate.getSystemDateToString());
                    ta.setUploadUser(user.getId());
                    list.add(ta);
                    
                } catch (Exception e) { 
                    stream =  null;
                    return new ReturnBean(false,e.getMessage());
                } 
            } else { 
               return new ReturnBean(false,"文件为空"); 
            } 
        } 
        taskAttachmentService.save(list);
        System.out.println(list);
		return new ReturnBean(true,"上传成功"); 
	}
	/**
	 * 根据任务id获取所有附件
	 * @param id
	 * @return
	 */
	@RequestMapping(value="getAllFileByTaskId.do")  
    public @ResponseBody List<TaskAttachmentVo> getAllFileByTaskId(@RequestParam("taskId") int id){
		return taskAttachmentService.getFileByTaskId(id);
	}
	/**
	 * 根据文件的路径下载文件
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/downloadFile.do")
	public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
	    //String fileName = "region.xls";
		String realPath = request.getParameter("fileRealPath");// 设置文件名，根据业务需要替换成要下载的文件名
	    if (realPath != null) {
	        //设置文件路径
	    	String fileName=realPath.substring(realPath.indexOf("_")+1, realPath.length());
			System.out.println(fileName);
	        File file = new File(realPath);
	        if (file.exists()) {
	            response.setContentType("application/force-download");// 设置强制下载不打开
	            //response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
	            response.setHeader("Content-Disposition", "attachment; fileName="+  fileName +";"
	            		+ "filename*=utf-8''"+URLEncoder.encode(fileName,"UTF-8")); //设置中文名称并且解决中文乱码问题 
	            byte[] buffer = new byte[1024];
	            FileInputStream fis = null;
	            BufferedInputStream bis = null;
	            try {
	                fis = new FileInputStream(file);
	                bis = new BufferedInputStream(fis);
	                OutputStream os = response.getOutputStream();
	                int i = bis.read(buffer);
	                while (i != -1) {
	                    os.write(buffer, 0, i);
	                    i = bis.read(buffer);
	                }
	                System.out.println("success");
	            } catch (Exception e) {
	                e.printStackTrace();
	            } finally {
	                if (bis != null) {
	                    try {
	                        bis.close();
	                    } catch (IOException e) {
	                        e.printStackTrace();
	                    }
	                }
	                if (fis != null) {
	                    try {
	                        fis.close();
	                    } catch (IOException e) {
	                        e.printStackTrace();
	                    }
	                }
	            }
	        }
	    }
	    return null;
	}
		
	
	
	
}
